package api.cie.rss.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.database.Cursor;
import api.cie.rss.common.Article;
import api.cie.rss.common.Category;
import api.cie.rss.common.RSS;
import api.cie.rss.dal.ArticleDAL;
import api.cie.rss.dal.CategoryDAL;
import api.cie.rss.dal.DatabaseAdapter;
import api.cie.rss.dal.RSS_CategoryDAL;
import api.cie.rss.dal.RssDAL;

/**
 * The class containing some useful functions
 * @author STL-API
 *
 */
public class Utils {
	final static SimpleDateFormat dateFormat = 
		new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z", Locale.US);
	
	public static Date dateFromString(String str) {
		try {
			Date tmp = dateFormat.parse(str);
			return tmp;
		} catch (ParseException e) {
			return new Date();
		}
	}
	
	public static String dateToString(Date date) {
		if (date == null) return "";
		return dateFormat.format(date);
	}
	
	public static void sortByDate(List<Article> origine) {
		Collections.sort(origine, new Comparator<Article>() {
			@Override
			public int compare(Article object1, Article object2) {
				if(object1.getPublishingDate().after(object2.getPublishingDate())) return -1;
				else return 1;
			}			
		});
	}
	
	public static void sortByTitle(List<Article> origine) {
		Collections.sort(origine, new Comparator<Article>() {
			@Override
			public int compare(Article object1, Article object2) {
				return object1.getTitle().compareTo(object2.getTitle());
			}			
		});
	}
	
	public static String processURL(String url) {
		String orgStr = "&";
		String replacingStr = "&#38;";
		String result = url.replaceAll(orgStr, replacingStr);
		return result;
	}
	
	public static String removeOccurence(String originalStr, String toRemove) {
		String result = originalStr;
		result = result.replaceAll(toRemove, "");
		return result;
	}
	
	/**
	 * Remove all tags of the defined type from a string
	 * @param originalStr
	 * @param tag
	 * @return
	 */
	public static String removeTag(String originalStr, String tag) {
		String startTag = "<" + tag;
		String endTag = "</" + tag + ">";
		String result = originalStr;
		while (true) {
			int pos = result.indexOf(startTag);			
			if (pos < 0) break;
			int posNext = result.indexOf(startTag, pos + 1);
			int posEnd = -1;
			int tmp = result.indexOf(endTag, pos); 
			posEnd = tmp < 0 ? -1 : (tmp + endTag.length());
			if ((posNext > 0 && posEnd > posNext) || posEnd == -1) {
				posEnd = result.indexOf("/>", pos) + 2;
			}
			result = result.substring(0, pos) + result.substring(posEnd);
		}		
		return result;
	}
	
	/**
	 * Format the summary so that it doesn't contain the tag <img> <a> <br/>
	 * @param summary
	 * @return
	 */
	public static String formatSummary(String summary) {
		if (summary == null || summary.equals("")) return "";
		String result = removeTag(summary, "img");
		result = removeTag(result, "a");
		result = removeOccurence(result, "<br/>");
		return result;
	}
	
	public static Article[] changeToArray(List<Article> list) {
		Article[] result = new Article[list.size()];
		for(int i=0; i<list.size(); i++) {
			result[i] = list.get(i);
		}
		return result;
	}
	
	public static Category convertToCategory(Cursor cursor) {
		if (cursor == null) return null;
		Category result = new Category();
		result.setId(cursor.getInt(cursor.getColumnIndex(CategoryDAL.KEY_ROWID)));
		result.setTitle(cursor.getString(cursor.getColumnIndex(CategoryDAL.KEY_TITLE)));
		
		return result;
	}
	
	public static RSS convertToRSS(Cursor cursor, DatabaseAdapter dbAdapter) {
		if (cursor == null) return null;
		RSS result = new RSS();
		result.setId(cursor.getInt(cursor.getColumnIndex(RssDAL.KEY_ROWID)));
		result.setUrl(cursor.getString(cursor.getColumnIndex(RssDAL.KEY_URL)));
		result.setTitle(cursor.getString(cursor.getColumnIndex(RssDAL.KEY_TITLE)));
		int active = cursor.getInt(cursor.getColumnIndex(RssDAL.KEY_ISACTIVE));
		boolean isActive = active == 0 ? false : true; 
		result.setActive(isActive);
		
		// set the categories for RSS
		List<Category> categories = new ArrayList<Category>();
		RSS_CategoryDAL dal = new RSS_CategoryDAL(dbAdapter);
		CategoryDAL categoryDAL = new CategoryDAL(dbAdapter);
		Cursor cursorCategory = dal.fetchByRSS(result.getId());
		if (cursorCategory != null) {
			for(int i=0; i<cursorCategory.getCount(); i++) {
				cursorCategory.moveToPosition(i);
				int idCategory = cursorCategory.getInt(cursorCategory.getColumnIndex(RSS_CategoryDAL.KEY_CATEGORY));
				categories.add(convertToCategory(categoryDAL.fetchCategory(idCategory)));
			}
		}
		result.setCategories(categories);
		return result;
	}
	
	public static Article convertToArticle(Cursor cursor, DatabaseAdapter dbAdapter) {
		if (cursor == null) return null;
		Article result = new Article();
		result.setTitle(cursor.getString(cursor.getColumnIndex(ArticleDAL.KEY_TITLE)));
		result.setId(cursor.getInt(cursor.getColumnIndex(ArticleDAL.KEY_ROWID)));
		result.setDescription(cursor.getString(cursor.getColumnIndex(ArticleDAL.KEY_DESCRIPTION)));
		result.setUrl(cursor.getString(cursor.getColumnIndex(ArticleDAL.KEY_URL)));
		result.setRating(cursor.getInt(cursor.getColumnIndex(ArticleDAL.KEY_RATINGS)));
		Date date = dateFromString(cursor.getString(cursor.getColumnIndex(ArticleDAL.KEY_DATE)));
		result.setPublishingDate(date);
		
		// set the RSS for the article
		int idRSS = cursor.getInt(cursor.getColumnIndex(ArticleDAL.KEY_IDRSS));
		RssDAL rssDAL = new RssDAL(dbAdapter);
		RSS rssOfArticle = convertToRSS(rssDAL.fetchRSS(idRSS), dbAdapter);
		result.setRss(rssOfArticle);
		
		return result;
	}
}
